<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="1200px"
  >
    <a-row>
      <a-col :span="12"
        ><a-card
          title="事故基础信息"
          :headStyle="{ fontSize: '14px', fontWeight: 'bold' }"
          :bordered="true"
          style="height: 100%"
        >
          <BasicForm @register="registerForm1"> </BasicForm> </a-card
      ></a-col>
      <a-col :span="12">
        <a-card
          title="“四不放过”处理原则"
          :headStyle="{ fontSize: '14px', fontWeight: 'bold' }"
          :bordered="trues"
          style="height: 100%"
        >
          <BasicForm @register="registerForm2"> </BasicForm> </a-card
      ></a-col>
    </a-row>
    <!-- <a-row>
      <a-card title="“四不放过”处理原则" :bordered="trues">
        <BasicForm @register="registerForm2"> </BasicForm>
      </a-card>
    </a-row> -->
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import {
    getAccidentRecord,
    addAccidentRecord,
    updateAccidentRecord,
  } from '/@/api/ehs/accidentRecord';
  import { addAccidentRecordSchema1, addAccidentRecordSchema2 } from './accidentrecord.data';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  const { createMessage } = useMessage();
  import { queryProjectUsersDetail } from '/@/api/project/user';
  import { useGlobSetting } from '/@/hooks/setting';
  const { globalProjectCode } = useGlobSetting();
  import moment from 'moment';
  export default defineComponent({
    name: 'AddOrUpdateAccidentRecord',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref<String>('');
      const orgcode = ref('');
      const unitOptions = ref([]);
      const [
        registerForm1,
        {
          setFieldsValue: setFieldsValue1,
          resetFields: resetFields1,
          validate: validate1,
          updateSchema: updateSchema1,
        },
      ] = useForm({
        labelWidth: 120,
        schemas: addAccidentRecordSchema1,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [
        registerForm2,
        {
          setFieldsValue: setFieldsValue2,
          resetFields: resetFields2,
          validate: validate2,
          updateSchema: updateSchema2,
        },
      ] = useForm({
        labelWidth: 120,
        schemas: addAccidentRecordSchema2,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
          orgcode.value = unrefData.orgcode;
        }
        resetFields1(); //重置表单
        resetFields2(); //重置表单
        setModalProps({ confirmLoading: false });
        queryUnitDivision({
          includechilds: true,
          isdept: false,
          flagisvalid: false,
          orgcode: orgcode.value,
        }).then((res) => {
          unitOptions.value = res;
          queryEnumOptions('EhsAccidentLevelEnum').then((res) => {
            console.log(unitOptions.value, 'unit');
            updateSchema1([
              {
                field: 'lvl',
                componentProps: {
                  getPopupContainer: (triggerNode) => document.body,
                  options: res[0].options.map((item) => {
                    return {
                      label: item.value,
                      value: Number(item.key),
                    };
                  }),
                },
              },
              {
                field: 'unitid',
                componentProps: {
                  getPopupContainer: (triggerNode) => document.body,
                  treeData: unitOptions.value,
                  fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                  listHeight: 150,
                  treeDefaultExpandAll: true, //默认展开
                  showCheckedStrategy: 'SHOW_ALL', //定义选中项回填的方式:默认只显示子节点;SHOW_ALL:显示所有选中节点(包括父节点);SHOW_PARENT:只显示父节点(当父节点下所有子节点都选中时).
                },
              },
            ]);
          });
        });

        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (operateType.value == OperationTypeEnum.EDIT) {
          getAccidentRecordById();
        }
      });
      /**
       * 返回弹窗标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      /**
       * 根据id获取静态信息
       */
      async function getAccidentRecordById() {
        getAccidentRecord(dataId.value)
          .then((res) => {
            console.log('res', res);
            setFieldsValue1({
              ...res,
              attachment: res.attachment ? JSON.parse(res.attachment) : [],
            });
            setFieldsValue2(res);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        const values = await validate1();
        const values2 = await validate2();
        values.orgcode = orgcode.value;
        values.tm = moment(values.tm).format('YYYY-MM-DD');
        values.attachment = JSON.stringify(values.attachment);
        values.unitname = treeToArray(unitOptions.value).find(
          (item) => item.unitid == values.unitid,
        )?.unitname;
        setModalProps({ confirmLoading: true });
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addAccidentRecord({ ...values, ...values2 })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
                setModalProps({ confirmLoading: false });
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateAccidentRecord({ ...values, ...values2 })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              setModalProps({ confirmLoading: false });
              // createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      onMounted(() => {});
      return {
        operateType,
        displayModuleTitle,
        registerModal,
        registerForm1,
        registerForm2,
        getAccidentRecordById,
        onButtonOkClick,
        opSuccess,
        unitOptions,
      };
    },
  });
</script>

<style scoped>
  ::v-deep(.ant-card-body) {
    padding: 15px 5px;
  }
  ::v-deep(.ant-card) {
    margin: 10px 5px;
  }
  ::v-deep(.ant-card-head-title) {
    padding: 12px;
  }
</style>
